<!DOCTYPE html>
<html lang="zh-CN">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>音频修复小工具</title>
    <script src="https://cdn.tailwindcss.com"></script>
    <link href="https://cdn.bootcdn.net/ajax/libs/daisyui/4.12.10/full.min.css" rel="stylesheet">
    <link href="https://cdn.bootcdn.net/ajax/libs/font-awesome/6.4.0/css/all.min.css" rel="stylesheet">
</head>
<body class="bg-gradient-to-br from-blue-50 to-indigo-100 min-h-screen">
    <div class="container mx-auto px-4 py-8 max-w-6xl">
        <!-- 标题区域 -->
        <div class="text-center mb-8">
            <h1 class="text-4xl font-bold text-gray-800 mb-2">
                <i class="fas fa-music text-blue-600 mr-3"></i>
                音频修复小工具
            </h1>
            <p class="text-gray-600">智能降噪，让您的音频更清晰</p>
        </div>

        <!-- 主要内容区域 -->
        <div class="grid grid-cols-1 lg:grid-cols-2 gap-8">
            <!-- 左侧：控制面板 -->
            <div class="bg-white rounded-xl shadow-lg p-6">
                <h2 class="text-2xl font-semibold mb-6 text-gray-800">
                    <i class="fas fa-cog text-blue-600 mr-2"></i>
                    控制面板
                </h2>

                <!-- 文件上传 -->
                <div class="mb-6">
                    <label class="block text-sm font-medium text-gray-700 mb-2">
                        选择音频文件
                    </label>
                    <input type="file" id="audioFile" accept=".mp3,.wav,.m4a" 
                           class="file-input file-input-bordered w-full max-w-xs">
                    <p class="text-sm text-gray-500 mt-1">支持格式：MP3, WAV, M4A</p>
                </div>

                <!-- 修复模式选择 -->
                <div class="mb-6">
                    <label class="block text-sm font-medium text-gray-700 mb-3">
                        修复模式
                    </label>
                    <div class="space-y-2">
                        <label class="label cursor-pointer">
                            <span class="label-text">一键修复</span>
                            <input type="radio" name="repairMode" value="auto" class="radio radio-primary" checked>
                        </label>
                        <label class="label cursor-pointer">
                            <span class="label-text">手动调节</span>
                            <input type="radio" name="repairMode" value="manual" class="radio radio-primary">
                        </label>
                    </div>
                </div>

                <!-- 降噪强度调节（手动模式显示） -->
                <div id="manualControls" class="mb-6 hidden">
                    <label class="block text-sm font-medium text-gray-700 mb-2">
                        降噪强度
                    </label>
                    <input type="range" id="noiseReduction" min="0" max="100" value="50" 
                           class="range range-primary">
                    <div class="flex justify-between text-xs text-gray-500 mt-1">
                        <span>轻微</span>
                        <span>中等</span>
                        <span>强力</span>
                    </div>
                </div>

                <!-- 处理按钮 -->
                <div class="space-y-3">
                    <button id="processBtn" class="btn btn-primary w-full" disabled>
                        <i class="fas fa-magic mr-2"></i>
                        开始修复
                    </button>
                    <button id="previewBtn" class="btn btn-secondary w-full" disabled>
                        <i class="fas fa-play mr-2"></i>
                        预览效果
                    </button>
                </div>

                <!-- 进度条 -->
                <div id="progressContainer" class="mt-6 hidden">
                    <div class="flex justify-between text-sm text-gray-600 mb-2">
                        <span>处理进度</span>
                        <span id="progressText">0%</span>
                    </div>
                    <progress id="progressBar" class="progress progress-primary w-full" value="0" max="100"></progress>
                </div>
            </div>

            <!-- 右侧：预览区域 -->
            <div class="bg-white rounded-xl shadow-lg p-6">
                <h2 class="text-2xl font-semibold mb-6 text-gray-800">
                    <i class="fas fa-headphones text-blue-600 mr-2"></i>
                    音频预览
                </h2>

                <!-- 原始音频 -->
                <div class="mb-6">
                    <h3 class="text-lg font-medium text-gray-700 mb-3">原始音频</h3>
                    <audio id="originalAudio" controls class="w-full">
                        <source src="" type="audio/mpeg">
                        您的浏览器不支持音频播放。
                    </audio>
                </div>

                <!-- 修复后音频 -->
                <div class="mb-6">
                    <h3 class="text-lg font-medium text-gray-700 mb-3">修复后音频</h3>
                    <audio id="processedAudio" controls class="w-full">
                        <source src="" type="audio/mpeg">
                        您的浏览器不支持音频播放。
                    </audio>
                </div>

                <!-- 下载按钮 -->
                <div class="space-y-3">
                    <button id="downloadBtn" class="btn btn-success w-full" disabled>
                        <i class="fas fa-download mr-2"></i>
                        下载修复音频
                    </button>
                    <button id="compareBtn" class="btn btn-info w-full" disabled>
                        <i class="fas fa-balance-scale mr-2"></i>
                        对比播放
                    </button>
                </div>

                <!-- 音频信息 -->
                <div id="audioInfo" class="mt-6 p-4 bg-gray-50 rounded-lg hidden">
                    <h4 class="font-medium text-gray-700 mb-2">音频信息</h4>
                    <div id="audioDetails" class="text-sm text-gray-600 space-y-1">
                        <!-- 动态填充音频信息 -->
                    </div>
                </div>
            </div>
        </div>

        <!-- 状态提示 -->
        <div id="statusMessage" class="mt-8 text-center hidden">
            <div class="alert alert-info inline-block">
                <i class="fas fa-info-circle mr-2"></i>
                <span id="statusText"></span>
            </div>
        </div>
    </div>

    <script>
        // 全局变量
        let currentFile = null;
        let processedFileUrl = null;
        let originalFileUrl = null;

        // DOM元素
        const audioFileInput = document.getElementById('audioFile');
        const processBtn = document.getElementById('processBtn');
        const previewBtn = document.getElementById('previewBtn');
        const downloadBtn = document.getElementById('downloadBtn');
        const compareBtn = document.getElementById('compareBtn');
        const originalAudio = document.getElementById('originalAudio');
        const processedAudio = document.getElementById('processedAudio');
        const progressContainer = document.getElementById('progressContainer');
        const progressBar = document.getElementById('progressBar');
        const progressText = document.getElementById('progressText');
        const statusMessage = document.getElementById('statusMessage');
        const statusText = document.getElementById('statusText');
        const audioInfo = document.getElementById('audioInfo');
        const audioDetails = document.getElementById('audioDetails');
        const manualControls = document.getElementById('manualControls');
        const noiseReduction = document.getElementById('noiseReduction');

        // 修复模式切换
        document.querySelectorAll('input[name="repairMode"]').forEach(radio => {
            radio.addEventListener('change', function() {
                if (this.value === 'manual') {
                    manualControls.classList.remove('hidden');
                } else {
                    manualControls.classList.add('hidden');
                }
            });
        });

        // 文件选择处理
        audioFileInput.addEventListener('change', function(e) {
            const file = e.target.files[0];
            if (file) {
                currentFile = file;
                originalFileUrl = URL.createObjectURL(file);
                originalAudio.src = originalFileUrl;
                
                // 启用按钮
                processBtn.disabled = false;
                previewBtn.disabled = false;
                
                // 显示音频信息
                showAudioInfo(file);
                showStatus('音频文件已加载，可以开始修复了！', 'info');
            }
        });

        // 显示音频信息
        function showAudioInfo(file) {
            const fileSize = (file.size / 1024 / 1024).toFixed(2);
            const fileType = file.type.split('/')[1].toUpperCase();
            
            audioDetails.innerHTML = `
                <div>文件名：${file.name}</div>
                <div>文件大小：${fileSize} MB</div>
                <div>文件格式：${fileType}</div>
            `;
            audioInfo.classList.remove('hidden');
        }

        // 显示状态信息
        function showStatus(message, type = 'info') {
            statusText.textContent = message;
            statusMessage.className = `mt-8 text-center`;
            const alertDiv = statusMessage.querySelector('.alert');
            alertDiv.className = `alert alert-${type} inline-block`;
            statusMessage.classList.remove('hidden');
            
            setTimeout(() => {
                statusMessage.classList.add('hidden');
            }, 5000);
        }

        // 开始修复处理
        processBtn.addEventListener('click', async function() {
            if (!currentFile) return;

            const formData = new FormData();
            formData.append('audio', currentFile);
            
            const repairMode = document.querySelector('input[name="repairMode"]:checked').value;
            formData.append('mode', repairMode);
            
            if (repairMode === 'manual') {
                formData.append('noise_reduction', noiseReduction.value);
            }

            // 显示进度条
            progressContainer.classList.remove('hidden');
            processBtn.disabled = true;
            previewBtn.disabled = true;

            try {
                const response = await fetch('http://localhost:8000/process-audio', {
                    method: 'POST',
                    body: formData
                });

                if (!response.ok) {
                    throw new Error('处理失败');
                }

                const result = await response.json();
                
                // 模拟进度更新
                updateProgress(0);
                for (let i = 0; i <= 100; i += 10) {
                    setTimeout(() => updateProgress(i), i * 100);
                }

                setTimeout(() => {
                    processedFileUrl = `http://localhost:8000${result.processed_url}`;
                    processedAudio.src = processedFileUrl;
                    
                    downloadBtn.disabled = false;
                    compareBtn.disabled = false;
                    
                    showStatus('音频修复完成！', 'success');
                    progressContainer.classList.add('hidden');
                    processBtn.disabled = false;
                }, 1500);

            } catch (error) {
                showStatus('处理失败：' + error.message, 'error');
                progressContainer.classList.add('hidden');
                processBtn.disabled = false;
            }
        });

        // 更新进度条
        function updateProgress(percent) {
            progressBar.value = percent;
            progressText.textContent = percent + '%';
        }

        // 预览效果
        previewBtn.addEventListener('click', function() {
            if (originalAudio.src && processedAudio.src) {
                // 播放原始音频前10秒
                originalAudio.currentTime = 0;
                originalAudio.play();
                
                setTimeout(() => {
                    originalAudio.pause();
                    // 播放修复后音频前10秒
                    processedAudio.currentTime = 0;
                    processedAudio.play();
                    
                    setTimeout(() => {
                        processedAudio.pause();
                    }, 10000);
                }, 10000);
                
                showStatus('正在对比播放前10秒音频...', 'info');
            } else {
                showStatus('请先处理音频文件', 'warning');
            }
        });

        // 对比播放
        compareBtn.addEventListener('click', function() {
            if (originalAudio.src && processedAudio.src) {
                // 同步播放两个音频
                originalAudio.currentTime = 0;
                processedAudio.currentTime = 0;
                originalAudio.play();
                processedAudio.play();
                
                showStatus('正在同步对比播放...', 'info');
                
                setTimeout(() => {
                    originalAudio.pause();
                    processedAudio.pause();
                }, 15000);
            }
        });

        // 下载修复音频
        downloadBtn.addEventListener('click', function() {
            if (processedFileUrl) {
                const link = document.createElement('a');
                link.href = processedFileUrl;
                link.download = 'repaired_audio.mp3';
                link.click();
                showStatus('音频下载开始！', 'success');
            }
        });

        // 页面卸载时清理URL
        window.addEventListener('beforeunload', function() {
            if (originalFileUrl) URL.revokeObjectURL(originalFileUrl);
        });
    </script>
</body>
</html>
